var tcp_server = require('./tcp_server/tcp_server');
var http_server = require('./http_server/http_server');
var s_db = require('./dbwrap_interface');
var schedule = require('node-schedule');
var moment = require('moment');
var sessions = require('./tcp_server/tcp_server');


tcp_server.tcp_server.listen(7777,function () {
    console.log('TCP  server is listenning on 7777');
});


//设置监听端口
http_server.listen(8051, "127.0.0.1", function () {
    console.log("HTTP server is started listen port 8051");
});

function timing() {
    console.log('scheduleCronstyle:' + new Date());
    //1. 查找数据库配置
    var getobj = {
        "tablename" : "timing",
    }
    s_db.db_get(getobj, function (status, ret) {
        if (status != 1)
            return;
        if (ret == null)
            return;
        ret.forEach( function(item,index){
            var nowTime = moment(new Date()).format('HH:mm');
            var startTime = item.start_time;
            var endTime = item.end_time;
            var icNum = item.ic_num;
            if (nowTime == startTime){
                if (sessions.sessions[icNum] != null) {
                    //发送启动命令
                    console.log("启动命令发送" ,icNum)

                    sessions.sessions[icNum].conn.write('ON\r\n');
                }else {
                    console.log("启动命令发送,设备未上线" ,icNum)
                }
            }
            if (nowTime ==endTime){
                if (sessions.sessions[icNum] != null) {
                    //发送关闭命令
                    console.log("关闭命令发送" ,icNum)

                    sessions.sessions[icNum].conn.write('OFF\r\n');
                }else {
                    console.log("启动命令发送,设备未上线" ,icNum)
                }
            }
        })


    })
}

function scheduleCronstyle(){
    schedule.scheduleJob('0 * * * * *', function(){
        timing();
    });
}

scheduleCronstyle();